﻿// -----------------------------------------------------------------------
// <copyright file="RestClientMessageInspector.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace DotNet37Signals.Client
{
    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;
    using System.Xml;
    using System.Xml.Xsl;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class RestClientMessageInspector : IClientMessageInspector
    {
        private XslCompiledTransform transform = null;

        #region IClientMessageInspector Members

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            // nothing
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (!request.IsEmpty)
            {
                XmlReader bodyReader = request.GetReaderAtBodyContents().ReadSubtree();

                MemoryStream stream = new MemoryStream();
                XmlWriter writer = XmlWriter.Create(stream);

                if (transform == null)
                {
                    transform = new XslCompiledTransform(true);
                    var reader = XmlReader.Create(new StringReader(Properties.Resources.XmlCleaner));
                    transform.Load(reader);
                }
                transform.Transform(bodyReader, writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                bodyReader = XmlReader.Create(stream);
                
                Message changedMessage = Message.CreateMessage(request.Version, null, bodyReader);
                changedMessage.Headers.CopyHeadersFrom(request.Headers);
                changedMessage.Properties.CopyProperties(request.Properties);
                request = changedMessage;
            }

            return null;
        }

        #endregion
    }
}
